//
//  NSObject+RBAdd.m
//  Tourist
//
//  Created by Lan on 2017/7/26.
//  Copyright © 2017年 SummerTea. All rights reserved.
//

#import "UIViewController+RBAdd.h"
#import "NSObject+YYAdd.h"
#import "RBDefine.h"
#import <Masonry.h>
#import "UIView+RBAdd.h"
#import "RBRequestHM.h"
#import <MJRefresh.h>
#import "RBPopVC.h"

static char *const RB_SINGLE_EDITING_KEY = "RB_SINGLE_EDITING_KEY";
static char *const RB_SINGLE_COMPLETION_KEY = "RB_SINGLE_COMPLETION_KEY";
//static char *const RB_MULTIPLE_EDITING_KEY = "RB_MULTIPLE_EDITING_KEY";
//static char *const RB_MULTIPLE_NUMBER_KEY = "RB_MULTIPLE_NUMBER_KEY";
static char *const RB_MULTIPLE_COMPLETION_KEY = "RB_MULTIPLE_COMPLETION_KEY";
static char *const RB_PHOTO_KEY = "RB_PHOTO_KEY";

@implementation UIViewController(RBAdd)

#pragma mark - Private

- (void)addVarWithKey:(char *const)key value:(id)value
{
    [self setAssociateValue:value withKey:key];
}

- (id)getVarWithKey:(char *const)key
{
    return [self getAssociatedValueForKey:key];
}

- (void)presentImageVCWithSourceType: (UIImagePickerControllerSourceType)type
{
    UIImagePickerController *vc = [UIImagePickerController new];
    vc.delegate = self;
    vc.sourceType = type;
    vc.allowsEditing = [[self getVarWithKey:RB_SINGLE_EDITING_KEY] boolValue];
    [self presentViewController:vc animated:YES completion:nil];
}

- (void)removeVars
{
    [self addVarWithKey:RB_SINGLE_EDITING_KEY value:nil];
    [self addVarWithKey:RB_SINGLE_COMPLETION_KEY value:nil];
}

#pragma mark - Public

- (void)chooseSingleImageAllowsEditing:(BOOL)allowsEditing title:(NSString *)title completion:(void (^)(UIImage *))completion
{
    [self addVarWithKey:RB_SINGLE_EDITING_KEY value:@(allowsEditing)];
    [self addVarWithKey:RB_SINGLE_COMPLETION_KEY value:completion];
    UIAlertController *alert = [UIAlertController alertControllerWithTitle:title message:nil preferredStyle:UIAlertControllerStyleActionSheet];
    [alert addAction:[UIAlertAction actionWithTitle:@"相册" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        [self presentImageVCWithSourceType:UIImagePickerControllerSourceTypePhotoLibrary];
    }]];
    if ([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera])
    {    
        [alert addAction:[UIAlertAction actionWithTitle:@"相机" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
            if ([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera])
            {
                [self presentImageVCWithSourceType:UIImagePickerControllerSourceTypeCamera];
            }
        }]];
    }
    [alert addAction:[UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:nil]];
    [self presentViewController:alert animated:YES completion:nil];
    
}

- (void)chooseSingleImageAllowsEditing:(BOOL)allowsEditing completion:(void (^)(UIImage *))completion
{
    [self chooseSingleImageAllowsEditing:allowsEditing title:@"选择图片" completion:completion];
}

- (void)presentVc: (UIViewController *)vc
{
    vc.providesPresentationContextTransitionStyle = YES;
    vc.definesPresentationContext = YES;
    vc.modalPresentationStyle = UIModalPresentationOverCurrentContext;
    [self presentViewController:vc animated:NO completion:nil];
}

#pragma mark - Delegate

- (void)imagePickerControllerDidCancel:(UIImagePickerController *)picker
{
    __weak typeof(self) weak_self = self;
    [picker dismissViewControllerAnimated:YES completion:^{
        void(^block)(UIImage *image) = [weak_self getVarWithKey:RB_SINGLE_COMPLETION_KEY];
        if (block)
        {
            block(nil);
        }
        [weak_self removeVars];
    }];
}

- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary<NSString *,id> *)info
{
    UIImage *image;
    if (picker.allowsEditing)
    {
        image = info[UIImagePickerControllerEditedImage];
    }
    else
    {
        image = info[UIImagePickerControllerOriginalImage];
    }
    void(^block)(UIImage *image) = [self getVarWithKey:RB_SINGLE_COMPLETION_KEY];
    if (block)
    {
        block(image);
    }
    [self removeVars];
    [picker dismissViewControllerAnimated:YES completion:nil];
}

@end

@implementation UIViewController(RBImageMultiplePick)

- (void)chooseImagesWithCount:(NSInteger)count completion:(void (^)(NSArray *))completion
{
    [self addVarWithKey:RB_MULTIPLE_COMPLETION_KEY value:completion];
    
    TZImagePickerController *vc = [[TZImagePickerController alloc] initWithMaxImagesCount:count delegate:self];
    vc.allowPreview = YES;
    vc.allowPickingGif = NO;
    vc.allowPickingVideo = NO;
    vc.allowPickingOriginalPhoto = NO;
    vc.allowTakePicture = NO;
    
    //    vc.photoWidth = 922;
    
    //    vc.barItemTextColor = [UIColor blackColor];
    //    vc.naviTitleColor = [UIColor blackColor];
    //    vc.navigationBar.tintColor = [UIColor blackColor];
    
    [self presentViewController:vc animated:YES completion:nil];
}

#pragma mark - TZImagePickerControllerDelegate

- (void)imagePickerController:(TZImagePickerController *)picker didFinishPickingPhotos:(NSArray<UIImage *> *)photos sourceAssets:(NSArray *)assets isSelectOriginalPhoto:(BOOL)isSelectOriginalPhoto
{
    if (photos.count)
    {
        void(^block)(NSArray *array) = [self getVarWithKey:RB_MULTIPLE_COMPLETION_KEY];
        if (block)
        {
            block(photos);
        }
    }
}

@end

@implementation UIViewController(RBPhoto)

- (void)showWithImages:(NSArray *)images index:(NSInteger)index imageViews:(NSArray *)imageViews
{
    RBPhotoBrowser *photo = [RBPhotoBrowser new];
    photo.startIndex = index;
    photo.showStyle = RBPhotoShowStyleZoom;
    photo.delegate = self;
    photo.imageViews = imageViews;
    photo.photoModels = ({
        NSMutableArray *arrayM = [NSMutableArray array];
        for (id data in images)
        {
            RBPhotoModel *model = [RBPhotoModel new];
            if ([data isKindOfClass:[NSString class]])
            {
                model.imageURLString = (NSString *)data;
            }
            else if ([data isKindOfClass:[UIImage class]])
            {
                model.image = (UIImage *)data;
            }
            [arrayM addObject:model];
        }
        arrayM;
    });
    [photo showWithCustomBlock:nil];
    [self addVarWithKey:RB_PHOTO_KEY value:photo];
}

#pragma mark - RBPhotoDelegate

- (void)rbPhoto:(nonnull RBPhotoBrowser *)photo didScrollToIndex:(CGFloat)index withPhotoController: (nonnull RBPhotoViewController *)controller
{
    UILabel *label = [controller getVarWithKey:"indexL"];
    if (!label && photo.photoModels.count > 1)
    {
        label = [UILabel new];
        label.font = [UIFont systemFontOfSize:13];
        label.textColor = [UIColor whiteColor];
        label.backgroundColor = [UIColor colorWithWhite:0 alpha:0.5];
        [label rbSetCornerRadius:12];
        label.textAlignment = NSTextAlignmentCenter;
        [controller addVarWithKey:"indexL" value:label];
        [controller.view addSubview:label];
        [label mas_makeConstraints:^(MASConstraintMaker *make) {
            make.top.mas_equalTo(kRBStatusBarHeight + 10);
            make.height.mas_equalTo(24);
            make.width.mas_equalTo(60);
            make.centerX.mas_equalTo(0);
        }];
    }
    [controller.view bringSubviewToFront:label];
    NSInteger currentIndex = (NSInteger)roundf(index) + 1;
    label.text = [NSString stringWithFormat:@"%zd/%zd", currentIndex, photo.photoModels.count];
}

- (void)rbPhoto:(RBPhotoBrowser *)photo singleTapGesture:(UITapGestureRecognizer *)gesture atPhotoView:(RBPhotoView *)photoView withPhotoController:(RBPhotoViewController *)controller
{
    UILabel *label = [controller getVarWithKey:"indexL"];
    [label removeFromSuperview];
}

@end

@implementation UIViewController(RBCommonSet)

#define kRBStatusBarStyleKey "kRBStatusBarStyleKey"
#define kRBIgnoreStatusAdjustKey "kRBIgnoreStatusAdjustKey"
#define kRBPageHiddenKey "kRBPageHiddenKey"

+ (void)load
{
    [self swizzleInstanceMethod:@selector(swizzledInitWithNibName:bundle:) with:@selector(initWithNibName:bundle:)];
    [self swizzleInstanceMethod:@selector(swizzledViewDidLoad) with:@selector(viewDidLoad)];
    [self swizzleInstanceMethod:@selector(swizzledViewWillAppear:) with:@selector(viewWillAppear:)];
    [self swizzleInstanceMethod:@selector(swizzledViewDidAppear:) with:@selector(viewDidAppear:)];
    [self swizzleInstanceMethod:@selector(swizzledViewWillDisappear:) with:@selector(viewWillDisappear:)];
    [self swizzleInstanceMethod:@selector(swizzledViewDidDisappear:) with:@selector(viewDidDisappear:)];
}

- (instancetype)swizzledInitWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    UIViewController *vc = [self swizzledInitWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    vc.modalPresentationStyle = UIModalPresentationFullScreen;
    return vc;
}

- (void)swizzledViewDidLoad
{
    [self swizzledViewDidLoad];
    NSString *className = NSStringFromClass([self class]);
    if ([className hasPrefix:@"RB"] && [className containsString:@"VC"])
    {
        //去掉返回按钮文字
        self.navigationItem.backBarButtonItem = [[UIBarButtonItem alloc] initWithTitle:@"" style:UIBarButtonItemStylePlain target:nil action:nil];
        //屏蔽11以下的自动调整
        self.automaticallyAdjustsScrollViewInsets = NO;
        if(!self.ignoreStatusAjust)
        {
            //状态栏颜色
            self.statusBarStyle = UIStatusBarStyleDefault;
        }
    }
}

- (void)setStatusBarStyle:(UIStatusBarStyle)statusBarStyle
{
    if([self isKindOfClass:RBPopVC.class])
    {
        return;
    }
    else if (self.presentingViewController && self.providesPresentationContextTransitionStyle == YES && self.definesPresentationContext == YES && self.modalPresentationStyle == UIModalPresentationOverCurrentContext)
    {
        return;
    }
    [self addVarWithKey:kRBStatusBarStyleKey value:@(statusBarStyle)];
    NSNumber *number = [self getVarWithKey:kRBPageHiddenKey];
    BOOL isHidden = number.boolValue;
    if (!isHidden)
    {
        dispatch_async(dispatch_get_main_queue(), ^{
            if (statusBarStyle == UIStatusBarStyleDefault)
            {
                if (@available(iOS 13.0, *))
                {
                    [UIApplication sharedApplication].statusBarStyle = UIStatusBarStyleDarkContent;
                }
                else
                {
                    [UIApplication sharedApplication].statusBarStyle = statusBarStyle;
                }
            }
            else
            {
                [UIApplication sharedApplication].statusBarStyle = statusBarStyle;
            }
        });
    }
}

- (UIStatusBarStyle)statusBarStyle
{
    //不是很准,尽量别用
    NSNumber *statusBarStyleNum = [self getVarWithKey:kRBStatusBarStyleKey];
    return statusBarStyleNum.integerValue;
}

- (void)setIgnoreStatusAjust:(BOOL)ignoreStatusAjust
{
    if(ignoreStatusAjust)
    {
        [self addVarWithKey:kRBIgnoreStatusAdjustKey value:@"1"];
    }
    else
    {
        [self addVarWithKey:kRBIgnoreStatusAdjustKey value:nil];
    }
}

- (BOOL)ignoreStatusAjust
{
    NSString *res = [self getVarWithKey:kRBIgnoreStatusAdjustKey];
    return [res isKindOfClass:NSString.class] && [res isEqualToString:@"1"];
}

- (void)swizzledViewWillAppear:(BOOL)animated
{
    [self addVarWithKey:kRBPageHiddenKey value:@(NO)];
    [self swizzledViewWillAppear: animated];
    if (![self isKindOfClass:[UINavigationController class]] && ![self isKindOfClass:[UITabBarController class]] && [NSStringFromClass(self.class) hasPrefix:@"RB"])
    {
        NSNumber *statusBarStyleNum = [self getVarWithKey:kRBStatusBarStyleKey];
        if (statusBarStyleNum)
        {
            self.statusBarStyle = statusBarStyleNum.integerValue;
        }
    }
}

- (void)swizzledViewDidAppear:(BOOL)animated
{
    [self swizzledViewDidAppear: animated];
    //iOS16 title bug
    [self.navigationController.navigationBar setNeedsLayout];
}

- (void)swizzledViewWillDisappear:(BOOL)animated
{
    [self addVarWithKey:"isHidden" value:@(YES)];
    [self swizzledViewWillDisappear: animated];
}

- (void)swizzledViewDidDisappear:(BOOL)animated
{
    [self swizzledViewDidDisappear: animated];
}

#pragma mark - Getter

- (RBRequestHM *)defaultHm
{
    char *const defaultHmKey = "defaultHmKey";
    RBRequestHM *hm = [self getVarWithKey:defaultHmKey];
    if (!hm)
    {
        hm = [RBRequestHM new];
        [self addVarWithKey:defaultHmKey value:hm];
    }
    return hm;
}

@end

@implementation UIViewController(RBLoadData)

- (void)viewLoadDataWithParam: (void(^)(NSMutableDictionary *dicM))paramSetupBlock
                         path: (NSString *)path
                         post: (BOOL)post
                          log: (BOOL)log
                responseClass: (Class)responseClass
                      desView: (UIView *)desView
                      showHud: (BOOL)showHud
              showPlaceHolder: (BOOL)showPlaceHolder
                     sucBlock: (void(^)(id data))sucBlock
                    failBlock: (void(^)(id data))failBlock
                  reloadBlock: (void(^)(void))reloadBlock
{
    [desView hidePlaceHolder];
    if (showHud)
    {
        [desView showProgressWithText:nil];
    }
    __weak typeof(desView) weakDesView = desView;
    [self.defaultHm requestWithParam:paramSetupBlock log:log post:post cancelLastRequest:NO fileParam:nil fileProgress:nil responseClass:responseClass pathName:path completion:^(RBResponse *response) {
        if (showHud)
        {
            [weakDesView hideHud];
        }
        if (response.succeed)
        {
            if (sucBlock)
            {
                sucBlock(response);
            }
        }
        else
        {
            if (failBlock)
            {
                failBlock(response);
            }
            if (showPlaceHolder)
            {
                [weakDesView showPlaceHolder:[response.message stringByAppendingString:@"\n点击刷新"] tapBlock:reloadBlock];
            }
        }
    }];
}

- (void)listLoadFirstPageWithDesView: (UIView *)desView
                     showPlaceHolder: (BOOL)showPlaceHolder
                            sucBlock: (void(^)(id data))sucBlock
                           failBlock: (void(^)(id data))failBlock
                         reloadBlock: (void(^)(void))reloadBlock
{
    __weak typeof(self) weakSelf = self;
    __weak typeof(desView) weakDesView = desView;
    [self.listView.mj_footer endRefreshing];
    [desView hidePlaceHolder];
    [self.defaultHm requestWithParam:^(NSMutableDictionary *dicM) {
        dicM[[self listPageKey]] = @"1";
        NSDictionary *params = [self listParams];
        for (NSString *key in params.allKeys)
        {
            dicM[key] = params[key];
        }
    } log:[self listLog] post:[self listPost] cancelLastRequest:NO fileParam:nil fileProgress:nil responseClass:[self listResponseClass] pathName:[self listRequestPath] completion:^(RBResponse *response) {
        [weakSelf.listView.mj_header endRefreshing];
        if (response.succeed)
        {
            response.currentPage = 1;
            if (sucBlock)
            {
                sucBlock(response);
            }
        }
        else
        {
            if (failBlock)
            {
                failBlock(response);
            }
            if (showPlaceHolder)
            {
                [weakDesView showPlaceHolder:[response.message stringByAppendingString:@"\n点击刷新"] tapBlock:reloadBlock];
            }
            else
            {
//                [weakDesView showTip:response.message completion:nil];
            }
        }
    }];
}

- (void)listLoadNextPageWithSucBlock: (void(^)(id data))sucBlock
                           failBlock: (void(^)(id data))failBlock
{
    __weak typeof(self) weakSelf = self;
    [self.listView.mj_header endRefreshing];
    [self.defaultHm requestWithParam:^(NSMutableDictionary *dicM) {
        dicM[[self listPageKey]] = @([self ListCurrentPage] + 1);
        NSDictionary *params = [self listParams];
        for (NSString *key in params.allKeys)
        {
            dicM[key] = params[key];
        }
    } log:[self listLog] post:[self listPost] cancelLastRequest:NO fileParam:nil fileProgress:nil responseClass:[self listResponseClass] pathName:[self listRequestPath] completion:^(RBResponse *response) {
        [weakSelf.listView.mj_footer endRefreshing];
        if (response.succeed)
        {
            response.currentPage = [weakSelf ListCurrentPage] + 1;
            if (sucBlock)
            {
                sucBlock(response);
            }
        }
        else
        {
            if (failBlock)
            {
                failBlock(response);
            }
        }
    }];
}

@end
